const { taskDetail, publishTask, editTask, getCycleRuleAll, earlyFinishTask, delTask } = require('../../../utils/task');

Page({
  data: {
    startDate: '',
    endDate: '',
    minDate: '',
    minEndDate: '',
    maxEndDate: '',
    cycleOptions: [], // {cycleRule, cycleCode}
    cycleIndex: 0,
    allowQuit: true,  // 默认允许中途退出
    isHot: false,
    isTop: false,
    checkInMustMedia: false,
    checkInRealTimeMedia: false,
    titleError: false,
    checkInRangeError: false,
    countDownError: false,
    isEdit: false,
    taskId: ''
  },
  async onLoad(options) {
    const now = new Date();
    const today = this.formatDate(now);
    const max = new Date(now.getTime() + 60 * 24 * 60 * 60 * 1000); // 最长60天
    const maxDay = this.formatDate(max);
    this.setData({
      minDate: today,
      minEndDate: today,
      maxEndDate: maxDay,
      startDate: today,
      endDate: today
    });
    // 获取周期列表
    try {
      const res = await getCycleRuleAll();
      const cycleOptions = (res || []).map(item => ({ cycleRule: item.cycleRule, cycleCode: item.cycleCode }));
      this.setData({ cycleOptions });
      // 如果是编辑，等周期列表加载后再回填
      if (options.taskId) {
        this.setData({ isEdit: true, taskId: options.taskId });
        wx.showLoading({ title: '加载中', mask: true });
        const detail = await taskDetail(options.taskId);
        wx.hideLoading();
        // 找到对应的周期index
        let cycleIndex = 0;
        if (cycleOptions.length) {
          const idx = cycleOptions.findIndex(opt => opt.cycleCode === detail.cycleCode);
          cycleIndex = idx > -1 ? idx : 0;
        }
        this.setData({
          title: detail.taskName || '',
          startDate: detail.taskStartTime ? detail.taskStartTime.substr(0, 10) : today,
          endDate: detail.taskEndTime ? detail.taskEndTime.substr(0, 10) : today,
          cycleIndex,
          checkInRange: detail.checkInStartTime && detail.checkInEndTime ? `${detail.checkInStartTime}-${detail.checkInEndTime}` : '',
          countDown: detail.checkInCountDownSeconds || '',
          desc: detail.taskDesc || '',
          quitMidwayFlag: detail.quitMidwayFlag === 'yes',
          isHot: detail.hotFlag  === 'yes',
          isTop: detail.topFlag  === 'yes',
          isPublic: detail.publicFlag === 'yes',
          checkInMustMedia: detail.checkInMustMedia === 'yes',
          checkInRealTimeMedia: detail.checkInRealTimeMedia === 'yes'
        });
      }
    } catch (e) {
      wx.showToast({ title: '获取周期失败：'+ e.data.msg, icon: 'none' });
    }
  },
  formatDate(date) {
    const y = date.getFullYear();
    const m = (date.getMonth() + 1).toString().padStart(2, '0');
    const d = date.getDate().toString().padStart(2, '0');
    return `${y}-${m}-${d}`;
  },
  onStartDateChange(e) {
    const val = e.detail.value;
    this.setData({ startDate: val, minEndDate: val });
    if (this.data.endDate < val) {
      this.setData({ endDate: val });
    }
  },
  onEndDateChange(e) {
    const val = e.detail.value;
    this.setData({ endDate: val });
  },
  onCycleChange(e) {
    this.setData({ cycleIndex: e.detail.value });
  },
  onSwitchChange(e) {
    const key = e.currentTarget.dataset.key;
    this.setData({ [key]: e.detail.value });
  },
  onTitleBlur(e) {
    const value = e.detail.value.trim();
    this.setData({ titleError: !value });
  },
  onCheckInRangeBlur(e) {
    const value = e.detail.value.trim();
    const valid = /^\d{2}:\d{2} 到 \d{2}:\d{2}$/.test(value);
    this.setData({ checkInRangeError: !value || !valid });
  },
  onCountDownBlur(e) {
    const value = e.detail.value.trim();
    const valid = value && !isNaN(Number(value)) && Number(value) >= 0;
    this.setData({ countDownError: !valid });
  },
  async onSubmit(e) {
    const values = e.detail.value;
    let hasError = false;
    // 校验任务标题
    if (!values.title) {
      this.setData({ titleError: true });
      hasError = true;
    } else {
      this.setData({ titleError: false });
    }
    // 校验打卡时间范围
    if (values.checkInRange && !/^\d{2}:\d{2}:\d{2}-\d{2}:\d{2}:\d{2}$/.test(values.checkInRange)) {
      this.setData({ checkInRangeError: true });
      hasError = true;
    } else {
      this.setData({ checkInRangeError: false });
    }
    // 校验倒计时
    if (values.countDown && (isNaN(Number(values.countDown)) || Number(values.countDown) < 0)) {
      this.setData({ countDownError: true });
      hasError = true;
    } else {
      this.setData({ countDownError: false });
    }
    if (hasError) {
      wx.showToast({ title: '请完善必填项', icon: 'none' });
      return;
    }
    // 组装参数
    const [checkInStartTime, checkInEndTime] = (values.checkInRange || '').split('-');
    const cycleOption = this.data.cycleOptions[this.data.cycleIndex] || {};
    const param = {
      taskName: values.title,
      taskStartTime: this.data.startDate + 'T00:00:00',
      taskEndTime: this.data.endDate + 'T23:59:59',
      cycleRule: cycleOption.cycleRule,
      cycleCode: cycleOption.cycleCode,
      checkInStartTime: checkInStartTime ? checkInStartTime.trim() : '',
      checkInEndTime: checkInEndTime ? checkInEndTime.trim() : '',
      checkInCountDownSeconds: values.countDown ? Number(values.countDown) : 0,
      taskDesc: values.desc,
      quitMidwayFlag: this.data.allowQuit ? 'yes' : 'no',
      hotFlag: this.data.isHot? 'yes' : 'no',
      topFlag: this.data.isTop? 'yes' : 'no',
      publicFlag: this.data.isPublic? 'yes' : 'no',
      checkInMustMedia: this.data.checkInMustMedia ? 'yes' : 'no',
      checkInRealTimeMedia: this.data.checkInRealTimeMedia ? 'yes' : 'no'
    };

    if (this.data.isEdit) {
      param.taskId = this.data.taskId;
    }
    
    try {
      if (this.data.isEdit) {
        await editTask(this.data.taskId, param);
        wx.showToast({ title: '编辑成功', icon: 'success' });
      } else {
        await publishTask(param);
        wx.showToast({ title: '发布成功', icon: 'success' });
      }
      // 打开上一页面并刷新数据
      this.openBack();
    } catch (e) {
      wx.showToast({ title: (this.data.isEdit ? '编辑' : '发布') + '失败:' + e.data.msg, icon: 'none' });
    }
  },

  /**
   * 提前结束任务
   */
  async onEarlyFinish() {
    wx.showModal({
      title: '确认提前结束',
      content: '确定要提前结束这个任务吗？此操作不可撤销，任务将立即结束。',
      confirmText: '确认结束',
      confirmColor: '#ff3b30',
      success: async (res) => {
        if (res.confirm) {
          try {
            await earlyFinishTask(this.data.taskId);
            wx.showToast({ title: '任务已结束', icon: 'success' });
            // 打开上一页面并刷新数据
            this.openBack();
          } catch (e) {
            console.error('异常：', e)
            wx.showToast({ 
              title: e.data.msg || '结束任务失败', 
              icon: 'none' 
            });
          }
        }
      }
    });
  },
  /**
   * 删除任务
   */
  async removeTask(){
    wx.showModal({
      title: '确认删除任务',
      content: '确定要删除这个任务吗？此操作不可撤销，任务将立即删除。',
      confirmText: '确认删除',
      confirmColor: '#ff3b30',
      success: async (res) => {
        if (res.confirm) {
          try {
            await delTask(this.data.taskId);
            wx.showToast({ title: '任务已删除', icon: 'success' });
            // 打开上一页面并刷新数据
            this.openBack();
          } catch (e) {
            wx.showToast({ 
              title: e.data.msg || '删除任务失败', 
              icon: 'none' 
            });
          }
        }
      }
    });
  },
  /**
   * 打开上一页面并刷新数据
   */
  openBack(){
     // 获取上一页实例并刷新
     const pages = getCurrentPages();
     const prevPage = pages[pages.length - 2];
     if (prevPage) {
       // 根据页面类型执行不同的刷新逻辑
       if (prevPage.route.includes('my-task')) {
         // 我的任务页面
         if (typeof prevPage.loadTasks === 'function') {
           prevPage.loadTasks(true);
         }
       } else if (prevPage.route.includes('task-detail')) {
         // 任务详情页面
         if (typeof prevPage.loadTaskDetail === 'function') {
           prevPage.loadTaskDetail();
         }
       } else {
         // 其他页面，尝试通用刷新方法
         if (typeof prevPage.refresh === 'function') {
           prevPage.refresh();
         } else if (typeof prevPage.onShow === 'function') {
           prevPage.onShow();
         }
       }
       
       // 设置刷新标记
       prevPage.setData({
         needRefresh: true
       });
     }
     
     // 延迟返回，让用户看到成功提示
     setTimeout(() => {
       wx.navigateBack();
     }, 800);
  }
}); 